<template>
    <div class="hls-video">
        <div ref="containerRef"></div>
        <div class="absolute left-2 top-2 max-w-[61%]">
            <transition name="slide-fade-left">
                <div v-show="state.error" class="flex error-panel justify-between shadow-lg shadow-[#0003]" row wrap
                     inline>
                    <span class="text-white">{{ state.error && state.error.message }}</span>
                    <a class="ml-4 text-[#01C2FF] hover:text-gray-300 flex-none" @click.stop="play">重试</a>
                </div>
            </transition>
        </div>
        <div v-if="title" class="title">{{ title }}</div>
    </div>
</template>

<script setup lang="ts">
import { onUnmounted, reactive, ref } from 'vue';
import type Jessibuca from 'public/jessibuca/jessibuca'

const props = defineProps<{
    src?: string,
    title?: string,
    controls?: boolean,
    muted?: boolean
}>()

const containerRef = ref<HTMLDivElement>()
const state = reactive({
    isLoading: false,
    error: null as Error | null
})
let jessibuca: Jessibuca | null = null;

function play() {
    jessibuca = new Jessibuca({
        container: containerRef.value!,
        videoBuffer: 0.2, // 缓存时长
        isResize: false,
        loadingText: "加载中",
        debug: true,
        decoder: '/jessibuca/decoder.js',
        showBandwidth: props.controls, // 显示网速
        operateBtns: props.controls ? {
            fullscreen: true,
            screenshot: true,
            play: false,
            audio: true
        } : {},
        forceNoOffscreen: false,
        isNotMute: !props.muted,
    });
    jessibuca.on('error', err => state.error = new Error(err))
    jessibuca.on('play', () => state.error = null)
    jessibuca!.play(props.src)
}

onUnmounted(() => {
    jessibuca?.destroy()
})
defineExpose({
    play,
    stop: () => jessibuca?.destroy()
})
</script>

<style scoped>
.hls-video {
    position: relative;
    background-color: #0004;
    background-image: url(./assets/image.png);
    background-size: 100% 100%;
}

.title {
    padding-left: 16px;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 32px;
    background: rgba(0, 0, 0, 0.6);
    font-size: 16px;
    line-height: 32px;
    /* identical to box height, or 125% */

    font-feature-settings: 'tnum' on, 'lnum' on;

    color: #E0F7FF;

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.error-panel {
    padding: 16px;
    border-radius: 4px;
    background: #222;
}
</style>